package main

import (
	_ "HTanfang/routers"
	_ "github.com/go-sql-driver/mysql"
	_ "anfang/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"net"
	"log"
	"HTanfang/mqtt_server"
	"fmt"
	"os"
	"github.com/astaxie/beego/plugins/cors"
	"HTanfang/cron"
)

func init() {
	env := os.Getenv("ENV_ANFANG")
	if env == "ONLINE" {
		beego.LoadAppConfig("ini", "conf/app_online.conf")
	} else {
		beego.LoadAppConfig("ini", "conf/app.conf")
	}
	orm.RegisterDataBase("default", "mysql", fmt.Sprintf(`%s:%s@tcp(%s)/%s?charset=utf8&loc=Local`, beego.AppConfig.String("mysqluser"), beego.AppConfig.String("mysqlpass"), beego.AppConfig.String("host"), beego.AppConfig.String("database")))
	orm.RunSyncdb("default", false, true)
}

func main() {
	setStaticPath()
	log.SetOutput(getLogfile("anfang.log"))
	beego.BConfig.WebConfig.Session.SessionOn = true
	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"PUT", "PATCH", "POST", "OPTIONS"},
		AllowHeaders:     []string{"Origin"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))
	go init_mqtt()
	go anfangcron.StartCheckOffline()
	go anfangcron.StartCheckPostData()
	beego.Run()
}

func setStaticPath() {
	beego.SetStaticPath("/js", "views/js")
	beego.SetStaticPath("/img", "views/img")
	beego.SetStaticPath("/css", "views/css")
	beego.SetStaticPath("/docs", "views/docs")
	beego.SetStaticPath("/fonts", "views/fonts")
	beego.SetStaticPath("/plugins", "views/plugins")
	beego.SetStaticPath("/assets", "views/assets")
	beego.SetStaticPath("/themes", "views/themes")
	beego.SetStaticPath("/third-party", "views/third-party")
	beego.SetStaticPath("/lang", "views/lang")

	beego.SetStaticPath("/uploads", beego.AppConfig.String("uploadspath"))
}

func init_mqtt() {
	l, err := net.Listen("tcp", beego.AppConfig.String("mqtthost"))
	if err != nil {
		log.Print("listen: ", err)
		return
	}
	mqtt_server.Mqtt_sv = mqtt_server.NewServer(l)
	mqtt_server.Mqtt_sv.Start()
	<-mqtt_server.Mqtt_sv.Done
}

func getLogfile(filepath string) (f *os.File) {
	var err error
	if !checkFileIsExist(filepath) {
		f, err = os.Create(filepath)
		if err != nil {
			panic(err)
		}
	} else {
		f, err = os.OpenFile(filepath, os.O_WRONLY | os.O_APPEND, 0666)
		if err != nil {
			panic(err)
		}
	}
	return
}
func checkFileIsExist(filename string) (bool) {
	var exist = true;
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false;
	}
	return exist;
}